package com.jy.wms.service;

import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.BaseService;
import com.jy.wms.common.base.ServiceException;
import com.jy.wms.common.base.SetAndModifyModel;
import com.jy.wms.common.base.SucessException;
import com.jy.wms.dao.*;
import com.jy.wms.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: WmsSplitService.java
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author Liyi
 * @Date Tue Oct 24 15:29:46 CST 2017
 */

@Service
public class WmsSplitService extends BaseService<WmsSplitMapper,WmsSplit> {

    @Autowired
    private WmsGoodsMapper wmsGoodsMapper;
    @Autowired
    private WmsSplitHistoryMapper wmsSplitHistoryMapper;
    @Autowired
    private WmsShipmentOrderMapper wmsShipmentOrderMapper;
    @Autowired
    private WmsShipmentRefundMapper wmsShipmentRefundMapper;

    /**
     * 插入一条记录
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsert( WmsSplit entity){
        return dao.baseInsert( entity );
    }

    /**
     * 插入一条记录（匹配有值的字段）
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsertSelective( WmsSplit entity){
        return dao.baseInsertSelective( entity);
    }

    /**
     * 删除（根据主键ID删除）
     * @param id 主键
     * @return int
     */
    public Integer baseDeleteByPrimaryKey( String id){
        return dao.baseDeleteByPrimaryKey( id);
    }

    /**
     *  删除（根据所属发运订单ID删除所属明细）
     * @param setAndModifyModel 所属发运订单ID
     * @return
     */
    @BaseServiceDescribe(moduleName = "拆单操作",btnName = "取消拆单")
    public Integer baseDeleteBySsfyddid( SetAndModifyModel setAndModifyModel,String cdr,String ckid)throws Exception{
        List<String> list = setAndModifyModel.getIds();
        //拆单表内已有发运订单的liet
        List<String> cdCount = new ArrayList<>();
        cdCount =  dao.getCdCount(list);
        WmsShipmentOrder wmsShipmentOrder = new WmsShipmentOrder();
        StringBuffer errMessage = new StringBuffer();
        Integer errCount = 0;
        if(cdCount.size() > 0){
            //根据采购订单IDS删除拆单数据
            dao.baseDeleteBySsfyddid(cdCount);
            //根据采购订单IDS修改采购订单拆单状态
            dao.updateShipmentOrderQxCdzt(cdCount);
            //删除原有的拆单历史记录
            wmsSplitHistoryMapper.baseDeleteBathPrimarySsfyddid(cdCount);
            //写入取消拆单历史记录
            for (String s : cdCount) {
                //新增拆单历史
                WmsSplitHistory wmsSplitHistory = new WmsSplitHistory();
                wmsSplitHistory.setId(UUIDUtils.uuid());
                wmsSplitHistory.setSsfyddid(s);
                wmsSplitHistory.setCdr(cdr);
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                wmsSplitHistory.setCdsj(sdf.format(new Date()));
                wmsSplitHistory.setCzlx("1");
                wmsSplitHistory.setCkid(ckid);
                wmsSplitHistoryMapper.insert(wmsSplitHistory);
            }
        }
        for (String s : list) {
            if(!cdCount.contains(s)){
                wmsShipmentOrder = wmsShipmentOrderMapper.selectById(s);
                if(errMessage.length() > 0){
                    errMessage.append("," + wmsShipmentOrder.getFybh());
                }else{
                    errMessage.append(",失败单号：" + wmsShipmentOrder.getFybh());
                }
                errCount++;
            }
        }
        throw new SucessException("取消拆单操作，成功"+cdCount.size()+ "条" + (errCount > 0 ? "失败"+ errCount + "条"+errMessage.toString()+"请确定发运订单已拆单": ""));
    }

    /**
     * 删除（根据ID 批量删除）
     * @param idList 主键ID列表
     * @return int
     */
    public Integer baseDeleteBathPrimaryKeys( List<String> idList){
        return dao.baseDeleteBathPrimaryKeys( idList );
    }

    /**
     * 显示SO关联的已退单未退货订单
     * @param id
     * @return
     */
    @BaseServiceDescribe(moduleName = "退单操作",btnName = "显示SO关联的已退单未退货订单")
    public List<WmsShipmentOrder> getSoGlList(String id,String hzid,String ckid){
        List<String> glid = wmsShipmentRefundMapper.getGlidBySoid(id);
        Map<String,Object> map = new HashMap<>();
        map.put("list",glid);
        map.put("hzid",hzid);
        map.put("ckid",ckid);
        if(glid.size()>0){
            return wmsShipmentRefundMapper.getSoList(map);
        }else{
            return wmsShipmentRefundMapper.getSoListSize0(map);
        }
    }

    /**
     * 修改发运订单 退单
     * @param setAndModifyModel
     * @return
     */
    @BaseServiceDescribe(moduleName = "退单操作",btnName = "退单")
    public void setTd(SetAndModifyModel setAndModifyModel) throws SucessException,ServiceException,Exception{
        StringBuffer message = new StringBuffer();
        for (String id : setAndModifyModel.getIds()) {
            WmsShipmentOrder wmsShipmentOrder = wmsShipmentOrderMapper.baseSelectByPrimaryKey(id);
            if(wmsShipmentOrder.getFyzt().equals("0")){
                dao.setTd(id);
            }else{
                message.append(" " + wmsShipmentOrder.getFybh());
            }
        }
        if(message.length() > 0){
            throw new SucessException("发运单号：" + message.toString() + "退单失败，请检查发运状态");
        }
        throw new SucessException();
    }
    /**
     * 修改发运订单 退单重报
     * @param setAndModifyModel
     * @return
     */
    @BaseServiceDescribe(moduleName = "退单操作",btnName = "退单重报")
    public void setTdzt(SetAndModifyModel setAndModifyModel) throws SucessException,ServiceException{
        WmsShipmentOrder wmsShipmentOrder = wmsShipmentOrderMapper.baseSelectByPrimaryKey(setAndModifyModel.getId());
        if((wmsShipmentOrder.getFyzt().equals("3") || wmsShipmentOrder.getFyzt().equals("4")) && wmsShipmentOrder.getThzt().equals("0")){
            dao.setFytd(setAndModifyModel.getId());
            throw new SucessException("退单成功");
        }else if(wmsShipmentOrder.getFyzt().equals("0")){
            List<String> list = setAndModifyModel.getIds();
            if(list!=null && list.size()>0){
                List<WmsShipmentRefund> refunds = new ArrayList<>();
                for (String s : list) {
                    if(dao.getCountBySoidAndGlid(setAndModifyModel.getId(),s) <= 0){
                        WmsShipmentRefund wmsShipmentRefund = new WmsShipmentRefund();
                        wmsShipmentRefund.setSoid(setAndModifyModel.getId());
                        wmsShipmentRefund.setId(UUIDUtils.uuid());
                        wmsShipmentRefund.setGlid(s);
                        refunds.add(wmsShipmentRefund);
                    }
                }
                wmsShipmentRefundMapper.baseInsertAll(refunds);
            }
            dao.setCstd(setAndModifyModel.getId());
            throw new SucessException("退单成功");
        }else{
            throw new ServiceException("退单失败，请检查发运订单状态是否为“初始/部分发运/全部发运”");
        }
    }

    /**
     * 分页查询
     * @param entity 实体
     * @return Page<WmsSplit>
     */
    public Page<Map<String,Object>> baseSelectPage(WmsSplit entity ){
        PageHelper.startPage(entity.getPage(),entity.getRows());
        return (Page<Map<String,Object>>)dao.baseSelectPage( entity );
    }

    /**
     * 查询（根据主键ID查询）
     * @param id 主键ID
     * @return WmsSplit
     */
    public WmsSplit baseSelectByPrimaryKey( String id ){
        return dao.baseSelectByPrimaryKey( id );
    }

    /**
     * 查询（根据ID 批量查询）
     * @param idList 主键ID列表
     * @return list
     */
    public Integer baseSelectBathPrimaryKeys( List<WmsSplit> idList ){
        return dao.baseSelectBathPrimaryKeys( idList );
    }

    /**
     *修改 （匹配有值的字段）
     * @param entity 主键ID列表
     * @return int
     */
    public Integer baseUpdateByPrimaryKeySelective( WmsSplit entity){
        return dao.baseUpdateByPrimaryKeySelective( entity);
    }

    /**
     *修改（根据主键ID修改）
     * @param entity 主键ID列表
     * @return int
     */
    public Integer baseUpdateByPrimaryKey( WmsSplit entity){
        return dao.baseUpdateByPrimaryKey( entity);
    }

    /**
     * 拆单
     * @param setAndModifyModel 所属发运订单ID列表
     * @return 0 成功 1订单未审核不可拆单
     */
    @BaseServiceDescribe(moduleName = "拆单操作",btnName = "拆单")
    @Transactional
    public void split(SetAndModifyModel setAndModifyModel,String cdr, String ckid)throws Exception{
        StringBuffer errMessage = new StringBuffer();
        //未拆单 已审核的IDS
        List<String> wcdIds = dao.getWcdCount(setAndModifyModel.getIds());
        //已拆单 或 未审核 或 退单状态为退单重报 的IDS
        List<String> ycdIds = dao.getYcdCount(setAndModifyModel.getIds());
        WmsShipmentOrder wmsShipmentOrder = new WmsShipmentOrder();
        for (String s : wcdIds) {
            wmsShipmentOrder.setId(s);
            //获取发运订单明细列表
            List<WmsShipmentOrderDetailed> shipmentDetList = dao.baseSelectBySsfyddid(s);
            for (WmsShipmentOrderDetailed wmsShipmentOrderDetailed : shipmentDetList) {
                //拆单只操作标识为“发运行”的明细
                if(wmsShipmentOrderDetailed.getBs().equals("0")){
                    Integer yqsl = Integer.valueOf(wmsShipmentOrderDetailed.getYqsl());
                    //创建拆单表实体并且加入发运订单ID
                    WmsSplit wmsSplit = new WmsSplit();
                    wmsSplit.setSsfyddid(s);
                    //找到对应的货品包装
                    WmsGoods wmsGoods = wmsGoodsMapper.baseSelectByPrimaryKey(wmsShipmentOrderDetailed.getHpid());
                    //找到的包装根据包装类型正序排序
                    List<WmsPackingDetailed> packingDetailedList = dao.selectPackingDetailedByBzid(wmsGoods.getBzid());
                    //箱包装计算数量
                    Integer jssl = yqsl;
                    for (int j = 2;j >= 0 ;j--){
                        //循环获取包装 箱包装2  内包装1  主单位0
                        WmsPackingDetailed wmsPackingDetailed = packingDetailedList.get(j);
                        //主单位数量 箱包装2  内包装1  主单位0
                        Integer zdwsl = Integer.valueOf(wmsPackingDetailed.getZdwsl());
                        //判断当前包装下的主单位必须大于0才能继续操作
                        if(zdwsl > 0){
                            //如果不是主单位的情况下
                            if(j!=0 && zdwsl!=0){
                                //计算取整数
                                Integer number = jssl/zdwsl;
                                //遍历加入拆单列表
                                if(number>0){
                                    for(int i = 0;i < number;i++){
                                        wmsSplit.setId(UUIDUtils.uuid());
                                        wmsSplit.setSsfymxid(wmsShipmentOrderDetailed.getId());
                                        wmsSplit.setHpid(wmsShipmentOrderDetailed.getHpid());
                                        wmsSplit.setSl(wmsPackingDetailed.getZdwsl());
                                        wmsSplit.setBzmxid(wmsPackingDetailed.getId());
                                        wmsSplit.setBzlx(String.valueOf(j));
                                        if(j == 2){
                                            wmsSplit.setZslx("0");
                                        }else{
                                            wmsSplit.setZslx("1");
                                        }
                                        wmsSplit.setC(wmsPackingDetailed.getC());
                                        wmsSplit.setK(wmsPackingDetailed.getK());
                                        wmsSplit.setG(wmsPackingDetailed.getG());
                                        wmsSplit.setTj(wmsPackingDetailed.getTj());
                                        wmsSplit.setBzzl(wmsPackingDetailed.getZl());
                                        wmsSplit.setFpzt("0");
                                        wmsSplit.setKwid(wmsShipmentOrderDetailed.getKwid().length()>0?wmsShipmentOrderDetailed.getKwid():null);
                                        wmsSplit.setPc(wmsShipmentOrderDetailed.getPc().length()>0?wmsShipmentOrderDetailed.getPc():null);
                                        wmsSplit.setScrq(wmsShipmentOrderDetailed.getScrq().length()>0?wmsShipmentOrderDetailed.getScrq():null);
                                        wmsSplit.setCkid(ckid);
                                        dao.baseInsertSelective(wmsSplit);
                                        jssl -= zdwsl;
                                    }
                                }
                            }else{
                                //如果是主单位的情况下，并且剩余的数量不为0
                                if(jssl!=0 && j == 0){
//                                    for(int i = 0;i < jssl;i++){
                                        wmsSplit.setId(UUIDUtils.uuid());
                                        wmsSplit.setSsfymxid(wmsShipmentOrderDetailed.getId());
                                        wmsSplit.setHpid(wmsShipmentOrderDetailed.getHpid());
                                        wmsSplit.setSl(String.valueOf(jssl));
                                        wmsSplit.setBzmxid(wmsPackingDetailed.getId());
                                        wmsSplit.setBzlx(String.valueOf(j));
                                        wmsSplit.setZslx("1");
                                        wmsSplit.setC(wmsPackingDetailed.getC());
                                        wmsSplit.setK(wmsPackingDetailed.getK());
                                        wmsSplit.setG(wmsPackingDetailed.getG());
                                        wmsSplit.setTj(wmsPackingDetailed.getTj());
                                        wmsSplit.setBzzl(wmsPackingDetailed.getZl());
                                        wmsSplit.setFpzt("0");
                                        wmsSplit.setKwid(wmsShipmentOrderDetailed.getKwid().length()>0?wmsShipmentOrderDetailed.getKwid():null);
                                        wmsSplit.setPc(wmsShipmentOrderDetailed.getPc().length()>0?wmsShipmentOrderDetailed.getPc():null);
                                        wmsSplit.setScrq(wmsShipmentOrderDetailed.getScrq().length()>0?wmsShipmentOrderDetailed.getScrq():null);
                                        wmsSplit.setCkid(ckid);
                                        dao.baseInsertSelective(wmsSplit);
//                                    }
                                }
                            }
                        }
                    }
                }
            }
            //修改发运订单状态为已拆单
            wmsShipmentOrder.setCdzt("1");
            wmsShipmentOrderMapper.baseUpdateByPrimaryKeySelective(wmsShipmentOrder);

            //新增拆单历史
            WmsSplitHistory wmsSplitHistory = new WmsSplitHistory();
            wmsSplitHistory.setId(UUIDUtils.uuid());
            wmsSplitHistory.setSsfyddid(s);
            wmsSplitHistory.setCdr(cdr);
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wmsSplitHistory.setCdsj(sdf.format(new Date()));
            wmsSplitHistory.setCzlx("0");
            wmsSplitHistory.setCkid(ckid);
            wmsSplitHistoryMapper.insert(wmsSplitHistory);
        }
        if(wcdIds.size()>0){
            dao.updateShipmentOrderCdzt(wcdIds);
        }
        for (String ycdId : ycdIds) {
            wmsShipmentOrder = wmsShipmentOrderMapper.selectById(ycdId);
            if(errMessage.length() > 0){
                errMessage.append("," + wmsShipmentOrder.getFybh());
            }else{
                errMessage.append(",失败单号：" + wmsShipmentOrder.getFybh());
            }
        }
        throw new SucessException("拆单操作，成功"+wcdIds.size()+ "条" + (ycdIds.size() > 0 ? "，失败"+ ycdIds.size() + "条"+errMessage.toString()+"请确定发运订单已审核且未拆单": ""));
    }

    /**
     * 分页查询
     *
     * @param entity 实体
     * @return Page<WmsShipmentOrder>
     */
    public Page<WmsShipmentOrder> getSoList(WmsShipmentOrder entity, String ckid, String hzid) {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PageHelper.startPage(entity.getPage(), entity.getRows());
        return (Page<WmsShipmentOrder>) dao.getSoList(entity, ckid, hzid);
    }

}
